package com.example.addemoone.fragment

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.example.addemoone.R

class ListFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list, container, false)
    }

    // 定义一个接口用于实现与Activity的通信，当选项被选中时触发
    interface OnItemSelectedListener {
        fun onItemSelected(itemId: Int)
    }

    // 创建接口的引用，用于后续调用方法
    private var listener: OnItemSelectedListener? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 给两个按钮绑定点击事件
        view.findViewById<Button>(R.id.item1).setOnClickListener { listener?.onItemSelected(1) }
        view.findViewById<Button>(R.id.item2).setOnClickListener { listener?.onItemSelected(2) }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 当Fragment被添加到Activity中时，将Activity的引用保存在接口的引用中
        if (context is OnItemSelectedListener) {
            listener = context
        } else {
            throw ClassCastException("$context 必须实现 OnItemSelectedListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        // 当Fragment从Activity中分离时，将Activity的引用置为null
        listener = null
    }

}